using Sustainalytics.SharedEntities.EsgResearch;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Sustainalytics.ClientDW.Synchronization.SyncESGData.RPIndicatorExtendedLogic
{
    public class RPIndicatorExtendedMapper
    {
        public IList<RPIndicatorExtended> MapOneToMany(EsgResearchProfile entity)
        {
            return entity.Indicators.Select(indicator => new RPIndicatorExtended
            {
                Id = Guid.NewGuid(),
                CompanyId = entity.Id,
                Comments = indicator.Comments,
                DataTable = MapDataTable(indicator),
                Number = indicator.Number,
                SelectedAnswer = indicator.SelectedAnswer,
                Tickboxes = indicator.Tickboxes,
                Trend = indicator.Trend,
                Weight = indicator.Weight,
                WeightedScore = indicator.WeightedScore,
            }).ToList();
        }

        private static SharedEntities.EsgResearch.Timestamped<IEnumerable<DataHistory>> MapDataTable(RPIndicatorExtended indicator)
        {
            var dataTable = indicator.DataTable;

            if (dataTable == null)
                return Timestamped(Enumerable.Empty<DataHistory>());

            return Timestamped(dataTable.Value ?? Enumerable.Empty<DataHistory>(), dataTable.Timestamp);
        }

        public IList<RPIndicatorExtended> MapManyToMany(IList<EsgResearchProfile> entities)
        {
            return entities.SelectMany(MapOneToMany).ToList();
        }

        private static SharedEntities.EsgResearch.Timestamped<T> Timestamped<T>(T value, DateTime? timestamp = null)
            => new SharedEntities.EsgResearch.Timestamped<T>() { Value = value, Timestamp = timestamp };
    };
}
